#!/bin/bash
# Creates a benchmark output for the prover in HTML and TeX format into html/.
# @author Zoltan Kovacs <zoltan@geogebra.org>

# Setting defaults.
MY_VERSION=2.1

IMGHEIGHT=25
HTML=html/all.html
TEX=html/all.tex
CSV=none
# Don't use this, it is just an example:
# COLUMNS="Recio PureSymbolic Botana,D BotanaGiac,D,p2 OpenGeoProver_Wu,p2 OpenGeoProver_Area Auto Web"
COLUMNS="Recio Botana Botana,D BotanaGiac BotanaGiac,D OpenGeoProver_Wu OpenGeoProver_Wu,D OpenGeoProver_Area Auto Auto,D Web Web,D"
TESTGGBURLBASE_GGBDIR=http://dev.geogebra.org/trac/browser/trunk/geogebra/test/scripts/benchmark/prover
GEOGEBRAWEB_URL1=https://www.geogebra.org/classic/?filename=https://dev.geogebra.org/trac/export
GEOGEBRAWEB_URL2=trunk/geogebra/test/scripts/benchmark/prover
SINGULARWSREMOTEURL=http://singularws.idm.jku.at/
USEENGINES=0
PROVEDETAILS=0
DOTS=20
NICEHTML=1
R_RUN=0

# R related settings. If there are more than 12 columns, this will not work. FIXME.
R_COL[1]=blue;	R_LTY[1]=1
R_COL[2]=red;	R_LTY[2]=1
R_COL[3]=black;	R_LTY[3]=1
R_COL[4]=black;	R_LTY[4]=2
R_COL[5]=black;	R_LTY[5]=3
R_COL[6]=red;	R_LTY[6]=2
R_COL[7]=darkgreen;	R_LTY[7]=1
R_COL[8]=darkgreen;	R_LTY[8]=2
R_COL[9]=blue;	R_LTY[9]=2
R_COL[10]=red;	R_LTY[10]=3
R_COL[11]=blue;	R_LTY[11]=3
R_COL[12]=darkgreen;	R_LTY[12]=3

COMMANDLINE="$0 $*"

usage() {
 echo "$0 - a benchmarking tool for GeoGebra's theorem prover subsystem"
 echo "Usage:"
 echo " xvfb-run $0 [options]"
 echo "  where options can be as follows (defaults in parentheses):"
 echo "   -S <name>    run scenario: 'name' can be one of the following: jar-paper, giac-test, ndg"
 echo "   -H <number>  image height: show .ggb thumbnails in the given number of pixels ($IMGHEIGHT)"
 echo "   -D           retrieve the ProveDetails results for all columns"
 echo "   -b <number>  use build number instead of the latest one for all columns"
 echo "   -o <file>    set name for output .html file ($HTML)"
 echo "   -T <file>    set name for output .tex file ($TEX)"
 echo "   -c <list>    space separated list of prover engines to show as columns ($COLUMNS)"
 echo "   -g <url>     use 'url' for putting links on test cases ($TESTGGBURLBASE_GGBDIR)"
 echo "   -s <url>     use 'url' to use non-default SingularWS ($SINGULARWSREMOTEURL)"
 echo "   -e           add introduction and use engine numbers in table headers"
 echo "   -d <length>  use dots in test names in LaTeX output if the name is longer than length ($DOTS)"
 echo "   -N           do not use nice HTML output (similarly to LaTeX)"
 echo "   -G           run R to create a density graph also"
 echo "   -P <file>    set portfolio database .csv file ($CSV)"
 echo "   -h           show this help"
 echo "   -v           print script version"
 echo
 echo "Examples:"
 echo " $0 -S jar-paper    # creates an output like at http://ggb1.idm.jku.at/~kovzol/data/Prove-20141009/"
 echo " $0 -S giac-test    # compares Prove output for Botana and BotanaGiac"
 echo " $0 -S giac-test -D # compares ProveDetails output for Botana and BotanaGiac"
 echo " $0 -S ndg          # compares ProveDetails output for Botana, BotanaGiac and OpenGeoProver_Wu"
 exit 0
 }

version() {
 echo "$0 version $MY_VERSION"
 exit 0
 }

while getopts "t:H:o:P:T:c:d:b:S:NeDGhv" OPT; do
 case $OPT in
  H)
   IMGHEIGHT="$OPTARG"
   ;;
  N)
   NICEHTML=0
   ;;
  o)
   HTML="$OPTARG"
   ;;
  d)
   DOTS="$OPTARG"
   ;;
  T)
   TEX="$OPTARG"
   ;;
  P)
   CSV="$OPTARG"
   ;;
  c)
   COLUMNS="$OPTARG"
   ;;
  S)
   case "$OPTARG" in
    jar-paper)
     COLUMNS="Recio Botana BotanaGiac OpenGeoProver_Wu OpenGeoProver_Area Auto"
     USEENGINES=1
     ;;
    giac-test)
     COLUMNS="Botana BotanaGiac"
     ;;
    ndg)
     COLUMNS="Botana BotanaGiac OpenGeoProver_Wu Auto"
     PROVEDETAILS=1
     ;;
   esac # -S
   ;;
  e)
   USEENGINES=1
   ;;
  g)
   TESTGGBURLBASE_GGBDIR="$OPTARG"
   ;;
  D)
   PROVEDETAILS=1
   ;;
  b)
   BUILD_NUMBER="$OPTARG"
   ;;
  G)
   R_RUN=1
   ;;
  h)
   usage
   ;;
  v)
   version
   ;;

 esac
done

# Put name of the filters into $@
shift $((OPTIND-1))

if [ "$BUILD_NUMBER" = "" ]; then
 BUILD_NUMBER=`sqlite3 sqlite3db "select max(build_number) from builds"`
 fi

COLUMNSNO=`echo $COLUMNS | wc -w`
THISDIR=`dirname $0`
MYDIR=`cd $THISDIR; pwd`
mkdir -p $MYDIR/tmp $MYDIR/html
LOGFILE=$MYDIR/tmp/.test.log
rm -f $HTML $TEX
R_PROG=$MYDIR/tmp/rprog

# Title
TITLE="Prover benchmark for GeoGebra $BUILD_NUMBER"
DATE=`date "+%Y-%m-%d %H:%M"`
SVN_REVISION=`sqlite3 sqlite3db "select svn_revision from builds where build_number=$BUILD_NUMBER"`
BUILD_URL=`sqlite3 sqlite3db "select build_url from builds where build_number=$BUILD_NUMBER"`
HOST=`sqlite3 sqlite3db "select machine from builds where build_number=$BUILD_NUMBER"`
echo "<!DOCTYPE html><html><head>
<title>$TITLE</title>
<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">
</head><body><h1>$TITLE</h1>
<h2>on $DATE at $HOST</h2>" >> $HTML
cp style.css `dirname $HTML`
echo "% Generated by '$COMMANDLINE' on $DATE.
% This file could be converted to PDF by using pdflatex.
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{multirow}
\usepackage{longtable}
\usepackage{array}
\begin{document}
\scriptsize{" >> $TEX

# Header
if [ "$USEENGINES" = 1 ]; then
 cat intro.html >> $MYDIR/$HTML
 fi
echo "<table><tr><th rowspan=\"2\" colspan=\"2\">Test file</th>" >> $MYDIR/$HTML
#RESULTCOLUMN=c
#if [ $PROVEDETAILS = 1 ]; then
 RESULTCOLUMN="m{1cm}"
# fi
echo "\begin{longtable}{|l|*{$COLUMNSNO}{${RESULTCOLUMN}r|}}
\hline
{\multirow{2}{*}{\bf Test}}" >> $MYDIR/$TEX

if [ "$CSV" != none ]; then
 TEST1=`ls -1 $MYDIR/tmp/.test.log-*-Recio-0 | head -1` # this should be newly generated, FIXME
 if [ "$TEST1" = "" ]; then
  echo "FATAL: $TEST1 does not exists, use portfolio-first-columns.sh first"
  exit 1
  fi
 CSV_HEADER=`cat $TEST1 | grep csv_header | cut -f5- -d" " | sed s/^csv_header:/test,/`
 echo -n $CSV_HEADER > $MYDIR/$CSV
 fi

for c in $COLUMNS; do
 j=`echo $c | cut -f1 -d,`
 r=`echo $c | cut -s -f2- -d,`

 if [ "$USEENGINES" = 1 ]; then
  case $j in
   Recio)
    TOPRINT="Engine 1"
    ;;
   Botana)
    TOPRINT="Engine 2"
    ;;
   BotanaGiac)
    TOPRINT="Engine 2, Giac"
    ;;
   OpenGeoProver_Wu)
    TOPRINT="Engine 3a"
    ;;
   OpenGeoProver_Area)
    TOPRINT="Engine 3b"
    ;;
   *)
    TOPRINT="$j"
    ;;
   esac
 else
  TOPRINT=`echo $j | sed s/"_"/" "/`
  fi
 if [ "$r" = "" ]; then
  FOOTHTML=""
  FOOTTEX=""
 else
  FOOTHTML="<br>$r"
  FOOTTEX="\\footnote{$r}"
  fi
 echo "<th colspan=\"2\">$TOPRINT$FOOTHTML</th>" >> $MYDIR/$HTML
 echo "& \multicolumn{2}{c|}{\bf $TOPRINT$FOOTTEX}" | sed s/OpenGeoProver/OGP/g |\
  sed s/BotanaGiac/Giac/ | sed s/Botana/Singular/ >> $MYDIR/$TEX
 done
echo "</tr><tr>" >> $MYDIR/$HTML
echo "\\\\" >> $MYDIR/$TEX

cn=0
declare -A COL_NDG
declare -A COL_BUILD_NUMBER
declare -A COL_J
declare -A COL_R

# Creating R input file
echo "library(sm); data = NULL; group = NULL;" > $R_PROG

# Creating column header related data
for c in $COLUMNS; do
 rm -f tmp/rinput-$c
 echo "<th>Result</th><th>Speed</th>" >> $MYDIR/$HTML
 echo "&R.&S." >> $MYDIR/$TEX
 cn=$((cn+1))
 j=`echo $c | cut -f1 -d,`
 r=`echo $c | cut -s -f2- -d,`
 ndg=0
 echo $r | grep --silent D && ndg=1
 if [ $PROVEDETAILS = 1 ]; then
  ndg=1
  fi
 build_number=$BUILD_NUMBER
 echo $r | grep --silent p && {
  PREV=`echo $r | awk '{i=index($0,"p"); print(substr($0,i+1))}'`
  build_number=`sqlite3 sqlite3db "select build_number from builds order by build_number desc limit 1 offset $PREV"`
  }
 echo $r | grep --silent b && {
  build_number=`echo $r | awk '{i=index($0,"b"); print(substr($0,i+1))}'`
  }
 COL_J[$cn]=$j
 COL_NDG[$cn]=$ndg
 COL_BUILD_NUMBER[$cn]=$build_number
 if [ "$CSV" != none ]; then
  echo -n ",$j $ndg,$j $ndg time" >> $MYDIR/$CSV
  fi
 done
if [ "$CSV" != none ]; then
 echo >> $MYDIR/$CSV
 fi

echo "</tr>" >> $MYDIR/$HTML
echo "\\\\ \hline" >> $MYDIR/$TEX

# Content
TESTS=0
ALLGOOD_NO=0
ALLGOOD_SUM=0
for t in `sqlite3 sqlite3db "select distinct testcase from tests where build_number=$BUILD_NUMBER"`; do
 echo -en "Processing test case $t...\033[K\015"
 ALLGOOD=1
 TESTS=`expr $TESTS + 1`
 # Creating thumbnail:
 cd $MYDIR
 i=`find -name $t.ggb`
 TEST=`basename $i`
 DIRNAME=`dirname $i | sed s/"^\.\/tests\/"/""/`
 unzip $i geogebra_thumbnail.png >/dev/null 2>&1
 mv geogebra_thumbnail.png html/$TEST.png
 # TODO: change "latest" to current revision:
 echo "<tr><td class=\"ex\"><a href=\"$TESTGGBURLBASE_GGBDIR/$i\">$TEST</a></td><td class=\"eximg\"><a href=\"${GEOGEBRAWEB_URL1}/latest/${GEOGEBRAWEB_URL2}/$i#\"><img src=\"$TEST.png\" height=${IMGHEIGHT}></a></td>" >> $MYDIR/$HTML
 TEST=`echo $TEST | sed s/".ggb"//`

 if [ "$CSV" != none ]; then
  POPULATION_DATA=`cat $MYDIR/portfolio-first-columns.txt | grep "^$TEST " | cut -f2- -d" "`
  if [ "$POPULATION_DATA" != "" ]; then
   echo -n "$TEST,$POPULATION_DATA" >> $MYDIR/$CSV
   fi
  fi

 if [ `expr ${#TEST} '>' $DOTS` = 1 ]; then
  TEST=${TEST:0:10}\$\\ldots\$${TEST:(-2)}
  fi
 echo "\cellcolor{blue!10}$TEST " | sed s/".ggb"// >> $MYDIR/$TEX

 declare -A RESULTDATA
 declare -A RESULTCLASSDATA
 declare -A CELLCOLORDATA
 declare -A TIMEDATA
 declare -A CORRECT
 declare -A SCORE
 BESTTIME=""
 WORSTTIME=""
 BESTPROVER=""
 WORSTPROVER=""
 CORRECT=""
 SCORE=""

 # First run: collecting data for a row
 cn=0
 for c in $COLUMNS; do
  cn=$((cn+1))
  j=${COL_J[$cn]}
  ndg=${COL_NDG[$cn]}
  build_number=${COL_BUILD_NUMBER[$cn]}

  FWCLAUSE=" from tests where build_number=$build_number and ndg=$ndg and prover='$j' and testcase='$t'"
  unset TIME
  unset RETVAL
  unset ACCEPTED
  unset ERRORTYPE
  unset RESULT
  TIME=`sqlite3 sqlite3db "select speed $FWCLAUSE"`
  RETVAL=`sqlite3 sqlite3db "select osresult $FWCLAUSE"`
  ACCEPTED=`sqlite3 sqlite3db "select accepted $FWCLAUSE"`
  ERRORTYPE=`sqlite3 sqlite3db "select errortype $FWCLAUSE"`
  RESULT=`sqlite3 sqlite3db "select result $FWCLAUSE"`

  RESULTCLASS=" class=\"o7\""
  CSVRESULT=0
  CELLCOLOR="green!10"
  DIRNAMELENGTH=${#DIRNAME}
  if [ "$ACCEPTED" = "" ]; then
   ALLGOOD=0
   if [ "$RESULT" = "" ]; then
    if [ "$ERRORTYPE" = 1 ]; then
    RESULTCLASS=" class=\"timeout\""
    CSVRESULT=-1
    CELLCOLOR="yellow!40"
    TIME="t/o"
    elif [ "$ERRORTYPE" = 0 ]; then
     RESULTCLASS=" class=\"undefined\""
     CELLCOLOR="yellow!25"
    else
     RESULTCLASS=" class=\"untested\""
     CSVRESULT=""
     CELLCOLOR="white!25"
     fi
   else
    RESULTCLASS=" class=\"undefined\""
    CELLCOLOR="yellow!25"
    fi
   fi
  if [ "$ACCEPTED" = "0" ]; then
   RESULTCLASS=" class=\"error\""
   CSVRESULT=""
   CELLCOLOR="red!25"
   ALLGOOD=0
   SCORE[$cn]="-1000000000000000" # -infty
   fi
  if [ "$ACCEPTED" = "1" ]; then
   VALUE=${CORRECT[$cn]}
   SCORE=${SCORE[$cn]}
   VALUE=$((VALUE+1))
   CORRECT[$cn]=$VALUE
   SCORE[$cn]=$((SCORE+20))
   if [ $TIME -lt 5000 ]; then
    RESULTCLASS=" class=\"o6\""
    CSVRESULT=1
    CELLCOLOR="green!15"
    SCORE[$cn]=$((SCORE+70))
    fi
   if [ $TIME -lt 1000 ]; then
    RESULTCLASS=" class=\"o5\""
    CELLCOLOR="green!20"
    SCORE[$cn]=$((SCORE+95))
    fi
   if [ $TIME -lt 300 ]; then
    RESULTCLASS=" class=\"o4\""
    CELLCOLOR="green!30"
    SCORE[$cn]=$((SCORE+97))
    fi
   if [ $TIME -lt 150 ]; then
    RESULTCLASS=" class=\"o3\""
    CELLCOLOR="green!40"
    SCORE[$cn]=$((SCORE+98))
    fi
   if [ $TIME -lt 50 ]; then
    RESULTCLASS=" class=\"o2\""
    CELLCOLOR="green!50"
    SCORE[$cn]=$((SCORE+99))
    fi
   if [ $TIME -lt 20 ]; then
    RESULTCLASS=" class=\"o1\""
    CELLCOLOR="green!60"
    SCORE[$cn]=$((SCORE+100))
    fi
   if [ $TIME -lt 5 ]; then
    ALLGOOD=0 # this is certainly the "true" case, it would distort density plot, so we ignore it
    fi
   fi
  RESULTCLASSDATA[$cn]=$RESULTCLASS
  CELLCOLORDATA[$cn]="$CELLCOLOR"
  RESULTDATA[$cn]="$RESULT"
  TIMEDATA[$cn]=$TIME
  CSVTIME=`echo $TIME | awk '{printf "%f", $1/1000}'`

  if [ "$CSV" != none -a "$POPULATION_DATA" != "" ]; then
   echo -n ",$CSVRESULT,$CSVTIME" >> $MYDIR/$CSV
   fi

  # Storing best and worst results
  if [ "$TIME" != "" -a "$RESULT" = "$DIRNAME" -a $j != Auto ]; then
   # First time result
   if [ "$BESTTIME" = "" ]; then
    BESTTIME=$TIME
    BESTPROVER=$c
   else
    # At least second time result
    if [ $TIME -lt $BESTTIME ]; then
     BESTTIME=$TIME
     BESTPROVER=$c
    else
     if [ "$WORSTTIME" = "" ]; then
      # Exactly the second time result
      WORSTTIME=$TIME 
      WORSTPROVER=$c
     else
      if [ $WORSTTIME -lt $TIME ]; then
       # More than second time result with worst current time
       WORSTTIME=$TIME
       WORSTPROVER=$c
       fi # end of >2, worst current
      fi # end of >2, not worst current
     fi # end of >=2
    fi # end of >=1, not best time current
   fi # end of >=1 (all cases)
  # echo "<td$RESULTCLASS>$RESULT</td><td$RESULTCLASS>$TIME</td>" >> $MYDIR/$HTML
  done # All provers done for this tests

 if [ "$CSV" != none -a "$POPULATION_DATA" != "" ]; then
  echo >> $MYDIR/$CSV
  fi

 # Second run: summarizing data in a row and generating HTML/LaTeX/R output
 cn=0
 for c in $COLUMNS; do
  cn=$((cn+1))
  j=${COL_J[$cn]}
  ndg=${COL_NDG[$cn]}

  RESULTCLASS=${RESULTCLASSDATA[$cn]}
  CELLCOLOR=${CELLCOLORDATA[$cn]}
  RESULT=${RESULTDATA[$cn]}
  if [ "$RESULT" = undefined -o "$RESULT" = "?" ]; then
   RESULT=""
   fi
  TIME=${TIMEDATA[$cn]}
  if [ "$ALLGOOD" = 1 ]; then
   echo "$TIME" >> tmp/rinput-$c
   ALLGOOD_SUM=$((ALLGOOD_SUM+TIME))
   ALLGOOD_NO=$((ALLGOOD_NO+1))
   fi
  SUMCLASS=""
  SUMCLASSTEX=""
  if [ "$WORSTPROVER" = "$c" ]; then
   SUMCLASS="worst"
   SUMCLASSTEX="\sl"
   fi
  if [ "$BESTPROVER" = "$c" ]; then
   SUMCLASS="best"
   SUMCLASSTEX="\bf"
   fi
  HTMLRESULT="$RESULT"
  if [ "$NICEHTML" = 1 ]; then
   TRUE=t
   if [ $ndg = 1 ]; then
    TRUE=""
    fi
   HTMLRESULT=`echo $HTMLRESULT | sed s/true/$TRUE/g | sed s/"^, "// | sed s/false/f/g`
   HTMLRESULT=`echo $HTMLRESULT | sed s/"AreEqual\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\\1=\\2"/g |\
    sed s/"AreParallel\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\\1\&#8741;\\2"/g |\
    sed s/"ArePerpendicular\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\\1\&#10178;\\2"/g |\
    sed s/"AreCongruent\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\\1\&#8773;\\2"/g |\
    sed s/"AreCollinear\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"<span class=\"overline\">\\1\\2\\3<\/span>"/g |\
    sed s/"_\([0-9]\+\)"/"<sub>\\1<\/sub>"/g` # Note that subscript change is the last one.
   fi
  echo "<td$RESULTCLASS>$HTMLRESULT</td><td$RESULTCLASS><p class=\"$SUMCLASS\">$TIME</p></td>" >> $MYDIR/$HTML
  # TeX related changes
  TRUE=t
  if [ $ndg = 1 ]; then
   TRUE=""
   fi
  RESULT=`echo $RESULT | sed s/true/$TRUE/g | sed s/"^, "// | sed s/false/f/g`
  RESULT=`echo $RESULT | sed s/"AreEqual\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\$\\1=\\2\$"/g |\
   sed s/"AreParallel\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\$\\1\\\\\\\\parallel \\2\$"/g |\
   sed s/"ArePerpendicular\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\$\\1\\\\\\\\perp \\2\$"/g |\
   sed s/"AreCongruent\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\$\\1\\\\\\\\cong \\2\$"/g |\
   sed s/"AreCollinear\[\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\),\([A-Za-z0-9_]\+\)\]"/"\$\\\\\\\\overline{\\1\\2\\3}\$"/g |\
   sed s/"\\\\$ \\\\$"/"\$\\\\\\\\hfill\\\\\\\\newline\$"/g |\
   sed s/"\.\.\."/"\$\\\\\\\\ldots\$"/g`
  if [ "$TIME" = timeout ]; then
   TIME="t/o"
   fi
  echo "& \cellcolor{$CELLCOLOR}$RESULT & \cellcolor{$CELLCOLOR}{$SUMCLASSTEX $TIME} " >> $MYDIR/$TEX
  done

 echo "</tr>" >> $MYDIR/$HTML
 echo "\\\\ \\hline" >> $MYDIR/$TEX
 done # All tests done

# Summary
echo "<tr><td class=\"summary\" colspan=\"2\"><b>Summary (of $TESTS)</b></td>" >> $MYDIR/$HTML
echo "{\bf Total (of $TESTS)}" >> $MYDIR/$TEX
ALLGOOD_MEAN=$((ALLGOOD_SUM/ALLGOOD_NO))
R_YMAX=`echo "scale=3; $COLUMNSNO/$ALLGOOD_NO" | bc -q` # FIXME
R_XMAX=$((ALLGOOD_MEAN*2))

cn=0
for c in $COLUMNS; do
 cn=$((cn+1))
 j=`echo $c | cut -f1 -d,`
 VALUE=${CORRECT[$cn]}
 if [ "$VALUE" = "" ]; then
  VALUE=0
  fi
 SCORE=${SCORE[$cn]}
 if [ "$SCORE" = "" ]; then
  SCORE=0
  fi
 if [ "${SCORE:0:1}" = "-" ]; then
  SCORE=error
  fi
 echo "<td class=\"summary\" colspan=\"2\"><b>$VALUE</b><br>$SCORE</td>" >> $MYDIR/$HTML
 echo "&\multicolumn{2}{c|}{\bf $VALUE}" >> $MYDIR/$TEX

 # Creating R based density graph. We use the r-cran-sm package under Ubuntu.
 R_COLNAME=`echo $c | sed s/,/__/g`
 LTY=${R_LTY[$cn]}
 COLOR=${R_COL[$cn]}
 if [ $cn = 1 ]; then
  PROVERSLIST="'$R_COLNAME'"
  COLSLIST="'$COLOR'"
  LTYSLIST="$LTY"
 else
  PROVERSLIST="$PROVERSLIST,'$c'"
  COLSLIST="$COLSLIST,'$COLOR'"
  LTYSLIST="$LTYSLIST,$LTY"
  fi
 echo "$R_COLNAME <- read.csv('$MYDIR/tmp/rinput-$c', header = F);" >> $R_PROG
 echo "sm.density($R_COLNAME,xlim=c(0,$R_XMAX),ylim=c(0,$R_YMAX),col='$COLOR',lty=$LTY,positive=TRUE,xlab='',ylab='');" >> $R_PROG
 echo "par(new=TRUE);" >> $R_PROG

 done
echo "</tr></table>" >> $MYDIR/$HTML

# Final R related computations
echo "legend('center','groups',c($PROVERSLIST),lty=c($LTYSLIST),col=c($COLSLIST),ncol=2,bty=\"n\");" >> $R_PROG
if [ "$R_RUN" = 1 ]; then
 cat $R_PROG | R -q --save && convert Rplots.pdf png:html/Rplots.png && \
  echo "<p class=figure><img src=Rplots.png></p>" >> $MYDIR/$HTML
 # TODO: Add this for LaTeX also.
 fi

echo "</tr>" >> $MYDIR/$HTML
echo "\\\\ \\hline" >> $MYDIR/$TEX

echo "</body></html>" >> $MYDIR/$HTML
echo "\end{longtable}
}
\end{document}" >> $MYDIR/$TEX

echo -e "$TESTS tests done.\033[K"
